import { PureComponent } from 'react';
import { Menu,Item,contextMenu } from 'react-contexify';
import { getNodeByKeyAndCallbackProcess } from '@/components/_utils/algorithmTools';
import {
	Tree,
  	Input,
	Icon,
} from 'antd';
const { Search } = Input;
const { TreeNode } = Tree;
import 'react-contexify/dist/ReactContexify.min.css';


class MenuAuthTree extends PureComponent {
	state = {
	    expandedKeys: [],
	    autoExpandParent: true,
	    checkedKeys: [],
	    selectedKeys: [],
	    defaultExpandedKeys: [],
	    selectedTreeByRightClick:"",
	    searchValue: '',
	    dataList: [],
	    sourceTreeNodeId:"",
	    treeData: [],
	    display:"block",
	};
	
	
	constructor(props) {
		super(props);
	}
	
 	componentDidMount() {
 		
    	this.onExpand(['000000000000']); // 手动触发，否则会遇到第一次不展开的Bug

    }
 	
	componentWillReceiveProps(nextProps) {
		if(undefined != nextProps.checkedKeys && nextProps.checkedKeys.list !== this.props.checkedKeys.list) {
	      this.setState({checkedKeys: nextProps.checkedKeys.list});
		}
		
		if(undefined != nextProps.menu && nextProps.menu.list !== this.props.menu.list) {
	      this.setState({treeData: nextProps.menu.list});
		}
	}
	
	//展开收起
	onExpand = expandedKeys => {
	    this.setState({
	      expandedKeys,
	      autoExpandParent: false,
	    });
	};
  
  	onCheck = (checkedKeys,info) => {
	  	const { checkedTreeChild } = this.props;
	  	checkedTreeChild(info);
	    this.setState({ checkedKeys });
  	};
  
  	onSelect = (selectedKeys, info) => {
    	this.setState({ selectedKeys });
  	};
    	
  	addMenuTreeNode = () => {
  		const { handleModalVisible } = this.props;
	    handleModalVisible(true,this.state.selectedTreeByRightClick);
	};
	
  	updateMenuTreeNode = () => {
  		const { handleUpdateModalVisible } = this.props;
	    handleUpdateModalVisible(true,this.state.selectedTreeByRightClick);
	};
	
  	viewMenuTreeNode = () => {
  		const { handleViewModalVisible } = this.props;
	    handleViewModalVisible(true,this.state.selectedTreeByRightClick);
	};
	
  	deleteMenuTreeNode = () => {
  		const { handleDeleteRecord } = this.props;
	    handleDeleteRecord(this.state.selectedTreeByRightClick);
	};
	
	RithtClickTreeNode = ({event,node}) => {
		event.preventDefault();
		contextMenu.show({
	      id: 'menu_id',
	      event: event,
	      props: {
	        foo: 'bar'
	      }
	    });

	    if(node.props.dataRef.key != '000000000000') {
	  		this.setState({ 
				selectedTreeByRightClick: node.props.dataRef,
				display:"block",
			});
	  	}else {
	  		this.setState({ 
				selectedTreeByRightClick: node.props.dataRef,
				display:"none",
			});
	  	}
	}

	MyAwesomeMenu = () => (
		<Menu id='menu_id' theme="light">
	       <Item onClick={this.addMenuTreeNode}>
	       		<Icon type="plus-circle" style={{fontSize: 16,paddingTop: 3}}/>
	       		<span style={{paddingLeft: 10}}>添加</span>
	       </Item>
	       <Item onClick={this.updateMenuTreeNode} style={{display: this.state.display}}>
		       <Icon type="edit" style={{fontSize: 16,paddingTop: 3}}/>
		       <span style={{paddingLeft: 10}}>修改</span>
	       </Item>
	       <Item onClick={this.viewMenuTreeNode} style={{display: this.state.display}}>
		       <Icon type="file-search" style={{fontSize: 16,paddingTop: 3}}/>
		       <span style={{paddingLeft: 10}}>查看</span>
	       </Item>
	       <Item onClick={this.deleteMenuTreeNode} style={{display: this.state.display}}>
	       		<Icon type="delete" style={{fontSize: 16,paddingTop: 3}}/>
	       		<span style={{paddingLeft: 10}}>删除</span>
	       	</Item>
	    </Menu>
	);
	
	onChange = e => {
		const { menu: { list } } = this.props;
	    const { value } = e.target;
	    const expandedKeys = this.state.dataList
	      .map(item => {
	        if (item.title.indexOf(value) > -1) {
	          return this.getParentKey(item.title, list);
	        }
	        return null;
	      }).filter((item, i, self) => item && self.indexOf(item) === i);
	    this.setState({
	      expandedKeys,
	      searchValue: value,
	      autoExpandParent: true,
	    });
	};
	
	getParentKey = (title, tree) => {
	  let parentKey;
	  for (let i = 0; i < tree.length; i++) {
	    const node = tree[i];
	    if (node.children) {
	      if (node.children.some(item => item.title === title)) {
	        parentKey = node.key;
	      } else if (this.getParentKey(title, node.children)) {
	        parentKey = this.getParentKey(title, node.children);
	      }
	    }
	  }
	  return parentKey;
	};
	

	generateList = data => {
	
	  if( undefined == data ){ return false;}

	  for (let i = 0; i < data.length; i++) {
	    const node = data[i];
	    const { key,title } = node;
	    this.state.dataList.push({ key, title: title });
	    if (node.children) {
	      this.generateList(node.children);
	    }
	  }
	};
	
	renderTreeNodes = data => {

	  if( undefined == data ){ return false;}

		
	   return data.map(item => {
		    const index = item.title.indexOf(this.state.searchValue);
	        const beforeStr = item.title.substr(0, index);
	        const afterStr = item.title.substr(index + this.state.searchValue.length);
	        const title =
	          index > -1 ? (
	            <span>
	              {beforeStr}
	              <span style={{ color: '#f50' }}>{this.state.searchValue}</span>
	              {afterStr}
	            </span>
	          ) : (
	            <span>{item.title}</span>
	          );
		      if (item.children) {
		        return (
		    	    <TreeNode title={title} key={item.key} dataRef={item}>
			            {this.renderTreeNodes(item.children)}
			         </TreeNode>
		        );
		      }
		      return <TreeNode {...item} dataRef={item} title={title} key={item.key}/>;
	  	});
	} 	
	
	onDrop = async ({event, node, dragNode, dragNodesKeys}) => {

		const levelcode = node.props.dataRef.levelcode;
		const dropKey = node.props.eventKey;
		const dragKey = dragNode.props.eventKey;
		const dragKey_parent_id = dragNode.props.dataRef.parentid;
		const new_levelcode = levelcode+"/"+dragKey;

	


		const data = [...this.state.treeData];




	   	let dragObj;

	   	getNodeByKeyAndCallbackProcess(data, dragKey,(item, index, arr) => {
	      arr.splice(index, 1);
	      dragObj = item;
	    });
	    
		//测试拖拽时候使用
	   /*getNodeByKeyAndCallbackProcess(data, dropKey,(item) => {

	        item.children = item.children || [];
	        // where to insert 示例添加到尾部，可以是随意位置
	        item.children.push(dragObj);
	   	});*/


		const { dispatch } = this.props;
		const levecode = this.state.targetTreeLevelCode + "/" + dragNode.props.id;
		await dispatch({
	        type: 'promenuauth/update_change_target_node_with_source_node_for_pro_menu',
	        payload:{
	        	source_parentid: dragKey_parent_id,
	        	source_id: dragKey,
	        	target_id: dropKey,
	        	levelcode: new_levelcode,
	        },
	        callback: (response) => {
	                 //持久化变拖拽时候使用
				    getNodeByKeyAndCallbackProcess(data, dropKey,(item) => {
				        item.children = item.children || [];
				        // where to insert 示例添加到尾部，可以是随意位置
				        item.children.push(response.datarecord||{});
				    });
	        }
	  	});


	   await this.setState({
      		treeData: data,
       });

	  
	}

  render() {
  	const { menu: { list } } = this.props;
  	
		const { autoExpandParent,expandedKeys,selectedKeys,checkedKeys,treeData } = this.state;
	
		this.generateList(list);
	    return (
	    	<div style={{float: 'right',width: '20%'}}>
	    	      <Search style={{ marginBottom: 8 }} placeholder="请输入菜单名称" onChange={this.onChange} />
			      <Tree
			      	checkable
			        onExpand={this.onExpand}
			        expandedKeys={expandedKeys}
			        autoExpandParent={autoExpandParent}
			        onCheck={this.onCheck}
			        checkedKeys={checkedKeys}
			        onSelect={this.onSelect}
			        selectedKeys={selectedKeys}
			        onRightClick={this.RithtClickTreeNode}
			        draggable
			        onDrop={this.onDrop}
			        >
			      		 {this.renderTreeNodes(treeData)}
			      </Tree>
			      {this.MyAwesomeMenu()}
	    	</div>
	    )
  }
 }

export default MenuAuthTree;